package agent;

import java.util.Collection;

import message.AlbumMsg;
import message.AlbumsMsg;
import message.ArtistMsg;
import message.ArtistsMsg;
import message.DbMsg;
import message.GetAlbumMsg;
import message.GetAlbumsMsg;
import message.GetArtistMsg;
import message.GetArtistsMsg;
import message.RemoveAlbumMsg;
import message.StoreAlbumMsg;
import model.Album;
import model.Artist;

import framework.Message;
import framework.agent.AbstractAgent;

public class DbAgent extends AbstractAgent {

	private static final String NAME = "BalkantonAgent";
	private static DbAgent sole;

	public static DbAgent getSole() {
		if (sole == null) {
			sole = new DbAgent(NAME);
		}
		return sole;
	}

	protected DbAgent(String agentName) {
		super(agentName);
	}

	@SuppressWarnings("unchecked")
	private <M extends Message> M sendAndReceiveMsg(Message msg) {
		return (M)sendAndWait(msg, "BalkantonService");
	}

	public Collection<Album> getAlbums() {
		Message request = new GetAlbumsMsg(getAgentName());
		AlbumsMsg responce = sendAndReceiveMsg(request);
		return responce.getAlbums();
	}

	public Collection<Artist> getArtists() {
		Message request = new GetArtistsMsg(getAgentName());
		ArtistsMsg responce = sendAndReceiveMsg(request);
		return responce.getArtists();
	}

	public Album getAlbum(String catalog) {
		Message request = new GetAlbumMsg(getAgentName(), catalog);
		AlbumMsg responce = sendAndReceiveMsg(request);
		return responce.getAlbum();
	}

	public Integer storeAlbum(Album album) {
		Message request = new StoreAlbumMsg(getAgentName(), album);
		DbMsg responce = sendAndReceiveMsg(request);
		return responce.getResult();
	}

	public Integer removeAlbum(String catalog) {
		Message request = new RemoveAlbumMsg(getAgentName(), catalog);
		DbMsg responce = sendAndReceiveMsg(request);
		return responce.getResult();
	}

	public Artist getArtist(String name) {
		Message request = new GetArtistMsg(getAgentName(), name);
		ArtistMsg responce = sendAndReceiveMsg(request);
		return responce.getArtist();
	}
}
